//
//  AppDelegate.m
//  BabyBluetoothAppDemo
//
//  Created by 刘彦玮 on 15/8/1.
//  Copyright (c) 2015年 刘彦玮. All rights reserved.
//

#import "AppDelegate.h"
#import <CoreBluetooth/CoreBluetooth.h>
#import "BabyBluetooth.h"
#import "PeripheralInfo.h"
#import "LoginViewController.h"
#import "SMMNav.h"
#import <SVProgressHUD.h>

@interface AppDelegate ()

@property(nonatomic,strong) LoginViewController *loginVC;
@property(nonatomic,strong) SMMNav *loginNav;

@end

@implementation AppDelegate
@synthesize peripherals,peripheralsAD,baby;
     
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [AVOSCloud setApplicationId:@"lzjdqv3dajojgtnbovjp9v2ih4wh3moozb9sd19w5e3lqgnk" clientKey:@"xdeo0fn0cz474giyrdr51d05pb3erhvtakc6wau5cr6n9slt"];
    [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
    
    NSArray *centralManagerIdentifiers = launchOptions[UIApplicationLaunchOptionsBluetoothCentralsKey];
    NSLog(@"%@",centralManagerIdentifiers);
    
    self.globalDBManager = [LKDBHelper getUsingLKDBHelper];//清空数据库
    [self.globalDBManager dropAllTable];
    self.myUserItem = [SpUserItem searchSingleWithWhere:nil orderBy:nil];
    if(!self.myUserItem)
    {
        self.myUserItem = [[SpUserItem alloc] init];
        [self.myUserItem saveToDB];
    }
    [SVProgressHUD setMinimumDismissTimeInterval:2.0f];
    
    self.netSession = [AFHTTPSessionManager manager];
    self.netSession.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
    //    self.netSession.requestSerializer = [AFJSONRequestSerializer serializer];
    self.netSession.responseSerializer = [AFHTTPResponseSerializer serializer];
    //初始化
    self.services = [[NSMutableArray alloc]init];
    //初始化其他数据 init other
    peripherals = [[NSMutableArray alloc]init];
    peripheralsAD = [[NSMutableArray alloc]init];
    self.currPeripheral = nil;
    baby = [BabyBluetooth shareBabyBluetooth];
//    [self babyDelegate];
    
    self.loginVC = [LoginViewController new];
    self.loginNav = [[SMMNav alloc] initWithRootViewController:self.loginVC];
    
    self.nowLevel = [tooles getPlistValueForKey:@"level"];
    self.hasBoughtLevel = [tooles getPlistValueForKey:@"bought"];
    NSLog(@"fffff:%d",self.nowLevel);
    
    self.vc = [[RootViewController alloc] init];
    self.vc.edgesForExtendedLayout = UIRectEdgeNone;
    SMMNav *nav = [[SMMNav alloc] initWithRootViewController:self.vc];
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.rootViewController = nav;
    [self.window makeKeyAndVisible];
    
    return YES;
}

//蓝牙网关初始化和委托方法设置
-(void)babyDelegate{
    
    __weak typeof(self) weakSelf = self;
    BabyRhythm *rhythm = [[BabyRhythm alloc]init];
    
    [baby setBlockOnCentralManagerDidUpdateState:^(CBCentralManager *central) {
        if (central.state == CBCentralManagerStatePoweredOn) {
            [SVProgressHUD showInfoWithStatus:@"蓝牙打开成功"];
        }
    }];
    
    //设置扫描到设备的委托
    [baby setBlockOnDiscoverToPeripherals:^(CBCentralManager *central, CBPeripheral *peripheral, NSDictionary *advertisementData, NSNumber *RSSI) {
        if(![weakSelf.peripherals containsObject:peripheral]) {
            NSLog(@"搜索到了设备:%@",peripheral.name);
            [weakSelf.peripherals addObject:peripheral];
            [weakSelf.peripheralsAD addObject:advertisementData];
            [weakSelf.myBlueTDelegate BlueTSucceed:@"device"];
        }
    }];
    
    //设置查找设备的过滤器
    [baby setFilterOnDiscoverPeripherals:^BOOL(NSString *peripheralName, NSDictionary *advertisementData, NSNumber *RSSI) {
        
        //最常用的场景是查找某一个前缀开头的设备
        //        if ([peripheralName hasPrefix:@"Pxxxx"] ) {
        //            return YES;
        //        }
        //        return NO;
        
        //设置查找规则是名称大于0 ， the search rule is peripheral.name length > 0
        if (peripheralName.length >0) {
            return YES;
        }
        return NO;
    }];
    
    
    [baby setBlockOnCancelAllPeripheralsConnectionBlock:^(CBCentralManager *centralManager) {
        NSLog(@"setBlockOnCancelAllPeripheralsConnectionBlock");
    }];
    
    [baby setBlockOnCancelScanBlock:^(CBCentralManager *centralManager) {
        NSLog(@"setBlockOnCancelScanBlock");
    }];
    
    //设置设备连接成功的委托,同一个baby对象，使用不同的channel切换委托回调
    [baby setBlockOnConnectedAtChannel:channelOnPeropheralView block:^(CBCentralManager *central, CBPeripheral *peripheral) {
        if([weakSelf.currPeripheral.name isEqualToString:peripheral.name]){
            [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"设备：%@ 连接成功",peripheral.name]];
            [weakSelf.myBlueTDelegate BlueTSucceed:@"service"];
        }else{
            [SVProgressHUD showInfoWithStatus:@"设备连接参数错误"];
        }
    }];
    
    [baby setBlockOnFailToConnectAtChannel:channelOnPeropheralView block:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"设备：%@--连接失败",peripheral.name]];
    }];
    
    //设置设备断开连接的委托
    [baby setBlockOnDisconnectAtChannel:channelOnPeropheralView block:^(CBCentralManager *central, CBPeripheral *peripheral, NSError *error) {
        NSLog(@"设备：%@--断开连接",peripheral.name);
        [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"设备：%@--断开失败",peripheral.name]];
    }];
    
    //设置发现设备的Services的委托
    [baby setBlockOnDiscoverServicesAtChannel:channelOnPeropheralView block:^(CBPeripheral *peripheral, NSError *error) {
        for (CBService *service in peripheral.services) {
            ///插入section到tableview
            NSLog(@"find service name:%@",service.UUID);
            PeripheralInfo *info = [[PeripheralInfo alloc]init];
            [info setServiceUUID:service.UUID];
            [weakSelf.services addObject:info];
        }
        [rhythm beats];
    }];
    
    //设置发现设service的Characteristics的委托
    [baby setBlockOnDiscoverCharacteristicsAtChannel:channelOnPeropheralView block:^(CBPeripheral *peripheral, CBService *service, NSError *error) {
        NSLog(@"+++service name:%@",service.UUID);
        for (int i=0;i<self.services.count;i++) {
            PeripheralInfo *info = [weakSelf.services objectAtIndex:i];
            if (info.serviceUUID == service.UUID) {
                for (int row=0;row<service.characteristics.count;row++) {
                    CBCharacteristic *c = service.characteristics[row];
                    [info.characteristics addObject:c];
                    if([c.UUID.UUIDString isEqualToString:MoshiUUID]){
                        weakSelf.MoshiChatic = c;
                    }else if([c.UUID.UUIDString isEqualToString:DangweiUUID]){
                        weakSelf.DangweiChatic = c;
                    }else if([c.UUID.UUIDString isEqualToString:KaiguanUUID]){
                        weakSelf.KaiguanChatic = c;
                    }else if([c.UUID.UUIDString isEqualToString:JiechuUUID]){
                        weakSelf.JiechuChatic = c;
                    }else if([c.UUID.UUIDString isEqualToString:DianliangUUID]){
                        weakSelf.DianliangChatic = c;
                    }
                }
            }
        }
    }];
    //设置读取characteristics的委托
    [baby setBlockOnReadValueForCharacteristicAtChannel:channelOnPeropheralView block:^(CBPeripheral *peripheral, CBCharacteristic *characteristics, NSError *error) {
        NSLog(@"characteristic name:%@-%@ value is:%@",characteristics.UUID,characteristics.UUID.UUIDString,characteristics.value);
        if([characteristics.UUID.UUIDString isEqualToString:MoshiUUID]||
           [characteristics.UUID.UUIDString isEqualToString:DangweiUUID]||
           [characteristics.UUID.UUIDString isEqualToString:KaiguanUUID]||
           [characteristics.UUID.UUIDString isEqualToString:JiechuUUID]||
           [characteristics.UUID.UUIDString isEqualToString:DianliangUUID]){
            if(weakSelf.finishBlock < 5){
                weakSelf.finishBlock++;
                if(weakSelf.finishBlock == 5){
                    [weakSelf.myBlueTDelegate BlueTSucceed:@"Chatic"];
                }
            }
        }
    }];
    //设置发现characteristics的descriptors的委托
    [baby setBlockOnDiscoverDescriptorsForCharacteristicAtChannel:channelOnPeropheralView block:^(CBPeripheral *peripheral, CBCharacteristic *characteristic, NSError *error) {
        NSLog(@"===characteristic name:%@",characteristic.service.UUID);
        for (CBDescriptor *d in characteristic.descriptors) {
            NSLog(@"CBDescriptor name is :%@",d.UUID);
        }
    }];
    //设置读取Descriptor的委托
    [baby setBlockOnReadValueForDescriptorsAtChannel:channelOnPeropheralView block:^(CBPeripheral *peripheral, CBDescriptor *descriptor, NSError *error) {
        NSLog(@"Descriptor name:%@ value is:%@",descriptor.characteristic.UUID, descriptor.value);
    }];
    
    //读取rssi的委托
    [baby setBlockOnDidReadRSSI:^(NSNumber *RSSI, NSError *error) {
        NSLog(@"setBlockOnDidReadRSSI:RSSI:%@",RSSI);
    }];
    
    //设置beats break委托
    [rhythm setBlockOnBeatsBreak:^(BabyRhythm *bry) {
        NSLog(@"setBlockOnBeatsBreak call");
        //如果完成任务，即可停止beat,返回bry可以省去使用weak rhythm的麻烦
        //        if (<#condition#>) {
        //            [bry beatsOver];
        //        }
        
    }];
    
    //设置beats over委托
    [rhythm setBlockOnBeatsOver:^(BabyRhythm *bry) {
        NSLog(@"setBlockOnBeatsOver call");
    }];
    
    //扫描选项->CBCentralManagerScanOptionAllowDuplicatesKey:忽略同一个Peripheral端的多个发现事件被聚合成一个发现事件
    NSDictionary *scanForPeripheralsWithOptions = @{CBCentralManagerScanOptionAllowDuplicatesKey:@YES};
    
    /*连接选项->
     CBConnectPeripheralOptionNotifyOnConnectionKey :当应用挂起时，如果有一个连接成功时，如果我们想要系统为指定的peripheral显示一个提示时，就使用这个key值。
     CBConnectPeripheralOptionNotifyOnDisconnectionKey :当应用挂起时，如果连接断开时，如果我们想要系统为指定的peripheral显示一个断开连接的提示时，就使用这个key值。
     CBConnectPeripheralOptionNotifyOnNotificationKey:
     当应用挂起时，使用该key值表示只要接收到给定peripheral端的通知就显示一个提
     */
    NSDictionary *connectOptions = @{
        CBConnectPeripheralOptionNotifyOnConnectionKey:@YES,
        CBConnectPeripheralOptionNotifyOnDisconnectionKey:@YES,
        CBConnectPeripheralOptionNotifyOnNotificationKey:@YES};
    [baby setBabyOptionsAtChannel:channelOnPeropheralView
    scanForPeripheralsWithOptions:scanForPeripheralsWithOptions
     connectPeripheralWithOptions:connectOptions
   scanForPeripheralsWithServices:nil
             discoverWithServices:nil
      discoverWithCharacteristics:nil];
    ///////////////////////////////////////////////
    
    //设置写数据成功的block
    [baby setBlockOnDidWriteValueForCharacteristicAtChannel:channelOnPeropheralView block:^(CBCharacteristic *characteristic, NSError *error) {
        NSLog(@"Write characteristic:%@ and new value:%@",characteristic.UUID.UUIDString, characteristic.value);
        //baby.channel(channelOnPeropheralView).characteristicDetails(weakSelf.currPeripheral,weakSelf.MoshiChatic);
    }];
    
    //设置通知状态改变的block
    [baby setBlockOnDidUpdateNotificationStateForCharacteristicAtChannel:channelOnPeropheralView block:^(CBCharacteristic *characteristic, NSError *error) {
        NSLog(@"uid:%@,isNotifying:%@",characteristic.UUID,characteristic.isNotifying?@"on":@"off");
    }];
}

-(void)loadDevice:(NSInteger)aIndex{
    //2902
    //停止扫描
    [self stopScanBlueT:nil];
    [self.services removeAllObjects];
    self.finishBlock = 0;
    self.currPeripheral = [self.peripherals objectAtIndex:aIndex];
    [SVProgressHUD showInfoWithStatus:@"开始连接设备"];
    baby.having(self.currPeripheral).and.channel(channelOnPeropheralView).then.connectToPeripherals().discoverServices().discoverCharacteristics().readValueForCharacteristic().discoverDescriptorsForCharacteristic().readValueForDescriptors().begin();
    //    baby.connectToPeripheral(self.currPeripheral).begin();
}

#pragma mark -蓝牙配置和操作

-(void)startToScanBlueT:(NSString*)aIAP{
    //停止之前的连接
    [baby cancelAllPeripheralsConnection];
    [self.services removeAllObjects];
    [peripherals removeAllObjects];
    [peripheralsAD removeAllObjects];
    //设置委托后直接可以使用，无需等待CBCentralManagerStatePoweredOn状态。
    baby.scanForPeripherals().begin();
    //baby.scanForPeripherals().begin().stop(10);
}
-(void)stopScanBlueT:(NSString*)aIAP{
    [baby cancelScan];
}

-(void)writeToChatic:(NSString*)aChatic withValue:(NSData*)aData{
    NSLog(@"want to write:%@ with:%@",aChatic,aData);
    if([aChatic isEqualToString:MoshiUUID]){
        [self.currPeripheral writeValue:aData forCharacteristic:self.MoshiChatic type:CBCharacteristicWriteWithResponse];
    }else if([aChatic isEqualToString:DangweiUUID]){
        [self.currPeripheral writeValue:aData forCharacteristic:self.DangweiChatic type:CBCharacteristicWriteWithResponse];
    }
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    NSLog(@"applicationWillResignActive");
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    NSLog(@"applicationDidEnterBackground");
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    NSLog(@"applicationWillEnterForeground");
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

-(void)dismissLoginWindow
{
    [self.window.rootViewController dismissViewControllerAnimated:YES completion:nil];
}

-(void)showLoginWindow
{
    [self.window.rootViewController presentViewController:self.loginNav animated:YES completion:nil];
}

@end
